package com.ruoyi.erp.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SortUtils;
import com.ruoyi.erp.common.enums.OrderStatus;
import com.ruoyi.erp.domain.XzgOrder;
import com.ruoyi.erp.domain.XzgOrderProduct;
import com.ruoyi.erp.domain.dto.XzgOrderExcelDto;
import com.ruoyi.erp.domain.vo.XzgOrderVo;
import com.ruoyi.erp.mapper.XzgCustomerMapper;
import com.ruoyi.erp.mapper.XzgOrderMapper;
import com.ruoyi.erp.mapper.XzgOrderProductMapper;
import com.ruoyi.erp.mapper.XzgProductMapper;
import com.ruoyi.erp.service.IXzgOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author qiuwencong
 * @Date 2021/12/6 10:36
 * @Package com.ruoyi.erp.service.impl
 * @Description
 */
@Service
public class XzgOrderServiceImpl implements IXzgOrderService {

    @Autowired
    private XzgOrderMapper orderMapper;

    @Autowired
    private XzgOrderProductMapper orderProductMapper;

    @Autowired
    private XzgProductMapper productMapper;

    @Autowired
    private XzgCustomerMapper customerMapper;

    @Override
    public int insertOrder(XzgOrder order) {
        if (selectSameCode(null, order.getOrderCode()).booleanValue()) {
            throw new ServiceException("合同号已存在");
        }
        return orderMapper.insertSelective(order);
    }

    @Override
    public List<XzgOrderVo> selectOrderList(XzgOrderVo order) {
        SortUtils.sort(order);
        return orderMapper.selectOrderList(order);
    }

    @Override
    public XzgOrder selectOrderById(Long orderId) {
        return orderMapper.selectByPrimaryKey(orderId);
    }

    @Override
    public int updateOrder(XzgOrder order) {
        return orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public Boolean selectSameCode(Integer orderId, String orderCode) {
        Integer count = orderMapper.selectSameCode(orderId, orderCode);
        return count > 0;
    }

    @Override
    public int changeOrderStatus(XzgOrder order, String orderStatus) {
        return orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOrderById(Long[] orderIds, String username) {
        List<XzgOrder> orders = orderMapper.selectByIds(orderIds);
        if (orders.stream().anyMatch(order -> "2".equals(order.getStatus()))) {
            throw new ServiceException("已完成的订单不能删除");
        }
        List<XzgOrderProduct> orderProducts = orderProductMapper.selectByOrderIds(orderIds);
        orderProductMapper.logicDeleteByOrderIds(orderIds, username);
        for (XzgOrderProduct orderProduct : orderProducts) {
            productMapper.updateStorageByProductId(orderProduct.getProductId(), orderProduct.getActualNum(), username);
        }
        return orderMapper.logicDeleteOrderById(orderIds, username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, List<String>> importOrders(List<XzgOrderExcelDto> orders, boolean updateSupport, String username) {
        List<String> insertSuccess = new ArrayList<>();
        List<String> updateSuccess = new ArrayList<>();
        List<String> fail = new ArrayList<>();
        for (XzgOrderExcelDto order : orders) {
            XzgOrder xzgOrder = orderMapper.selectByOrderCode(order.getOrderCode());
            Long customerId = getCustomerId(order.getCustomerName(), order.getDepartment(), order.getCompany());
            if (Objects.isNull(customerId)) {
                fail.add("编号为：" + order.getOrderCode() + "的客户不存在");
                continue;
            }
            if (Objects.isNull(xzgOrder)) {
                XzgOrder xzgOrder1 = new XzgOrder();
                xzgOrder1.setCustomerId(customerId);
                xzgOrder1.setUpdateTime(new Date());
                xzgOrder1.setUpdateBy(username);
                xzgOrder1.setCreateTime(new Date());
                xzgOrder1.setCreateBy(username);
                conventOrder(xzgOrder1, order);
                orderMapper.insertSelective(xzgOrder1);
                insertSuccess.add(order.getOrderCode());
            } else if (updateSupport) {
                xzgOrder.setUpdateTime(new Date());
                xzgOrder.setUpdateBy(username);
                conventOrder(xzgOrder, order);
                orderMapper.updateByPrimaryKeySelective(xzgOrder);
                updateSuccess.add(order.getOrderCode());
            } else {
                fail.add("编号为：" + order.getOrderCode() + "的数据已存在");
            }
        }
        Map<String, List<String>> map = new HashMap<>(3);
        map.put("insert", insertSuccess);
        map.put("update", updateSuccess);
        map.put("fail", fail);
        return map;
    }

    private void conventOrder(XzgOrder order, XzgOrderExcelDto excelOrder) {
        order.setStatus(OrderStatus.getKeyByValue(excelOrder.getStatus()));
        order.setUserId(excelOrder.getUserId());
        order.setDeleted("0");
        order.setDeliveryTime(excelOrder.getDeliveryTime());
        order.setOrderCode(excelOrder.getOrderCode());
        order.setTotalPrice(excelOrder.getTotalPrice());
        order.setRemark(excelOrder.getRemark());
    }

    private Long getCustomerId(String customerName, String department, String company) {
        return customerMapper.selectByNameAndDepartmentAndCompany(customerName, department, company);
    }

}
